Page({
  data: {
    sell_name:'',
    socketTask: '',
    inputValue: '',
    messages:[],
    sellAvatar: '',
    buyAvatar: '',
    sell_id: '',
    buy_id: '',
    mode: '',
    page:0
  },

  onLoad(options) {
    var that = this;
    wx.request({
      url: 'https://9p47q51245.goho.co/find-author',
      method: 'POST',
      data: {
        openId: options.openId,
        detailId: options.detailId
      },
      success: function (res) {
        console.log(res)
        console.log("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
        if (res.data && res.data.sell_id) {
         that.setData({
          sell_id : res.data.sell_id,
          buy_id :res.data.buy_id,
          sellAvatar : res.data.sell_img,
          buyAvatar :res.data.buy_img,
          sell_name:res.data.sell_name
         })
          that.connectSocket(that.data.sell_id, that.data.buy_id,that.data.page);
          
        }
      },
      fail: function (err) {
        console.error('Request failed:', err);
      }
    });
  },

  connectSocket(sell_id, buy_id,page) {
    var that = this;
    this.socketTask = wx.connectSocket({
      url: 'wss://9p47q51245.goho.co/ws/communication/' + sell_id + "/" + buy_id+'/'+page,
      success: (res) => {
        console.log('WebSocket连接成功');
      },
      fail: () => {
        console.log('WebSocket连接失败');
      }
    });

    wx.onSocketMessage((message) => {
      console.log('收到服务器内容：' + message.data);
      this.handleReceivedMessage(message.data);
    });

    wx.onSocketOpen(() => {
      console.log('WebSocket连接已打开');
    });
  },

  handleReceivedMessage(messageData) {
    var that=this
    try {
      const messageObj = JSON.parse(messageData);
      console.log(messageObj)
      if(messageObj['messages']){
        that.setData({
          page:messageObj['messages'][0]['page']+1
        })
        var length=messageObj['messages'].length
        for(var i=0;i<length;i++){
          console.log(messageObj['messages'][i])
          var detail=messageObj['messages'][i]
          const content = detail['message'];
          const timestamp = detail['timestamp'];
          const pattern = detail['pattern'];
          const mode = pattern === 'me' ? 1 : 0;
          const message = {
            content: content,
            timestamp: timestamp,
            mode: mode
          };  
            this.data.messages.unshift(message);
          
        }
      } else if (messageObj['message']) { // 检查是否是单个消息对象
        this.processMessage(messageObj['message']);
      }
      //this.sortMessages();
  
      this.setData({
        messages: this.data.messages
      });
    } catch (e) {
      console.error('消息解析失败', e);
    }
    this.scrollToBottom();
  },
  
  processMessage(detail) {
    const content = detail['message'];
    const timestamp = detail['timestamp'];
    const mode1 = detail['mode']
    console.log(mode)
    if (mode1==this.data.buy_id){
      var mode=1
    }
    else{
      var mode=0
    }
    console.log(this.data.mode)

    const message = {
      content: content,
      timestamp: timestamp,
      mode: mode
    };
      this.data.messages.push(message);
  },
  sortMessages() {
    this.data.me_messages.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
    this.data.you_messages.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
  },

  handleInput(event) {
    this.setData({
      inputValue: event.detail.value
    });
  },

  sendSocketMessage() {
    const messageStr = JSON.stringify({ 'message': this.data.inputValue, 'mode':this.data.buy_id, 'timestamp': new Date().toISOString() });
    wx.sendSocketMessage({
      data: messageStr,
      success: () => {
        console.log('消息发送成功');
        this.handleReceivedMessage(messageStr); // 假设发送的消息格式与接收到的相同
        this.setData({
          inputValue: ''
        });
      },
      fail: () => {
        console.log('消息发送失败');
      }
    });
  },

  scrollToBottom() {
    this.setData({
      scrollToView: 'bottom'
    });
  },
  onReady() {
    // 页面初次渲染完成时，也滚动到底部
    this.scrollToBottom1();
  },

  // ...其他代码保持不变

  scrollToBottom1() {
    // 设置一个延迟，以确保页面内容已经渲染
    setTimeout(() => {
      this.setData({
        scrollToView: 'bottom'
      });
    }, 100); // 延迟100毫秒，这个值可能需要根据实际情况调整
  },
  onPullDownRefresh: function() {
    var that = this;
    this.setData({ isRefreshing: true }); // 开始刷新
    wx.showLoading({ title: '加载中...', mask: true }); // 显示加载动画
    wx.closeSocket({
      success: () => {
        console.log('WebSocket已断开连接');
      },
      fail: (err) => {
        wx.showToast({
          title: '没有更多内容了',
          icon: 'none'
        });
      }
    });
    // 重新连接 WebSocket
    this.connectSocket(this.data.sell_id, this.data.buy_id, this.data.page);
    wx.stopPullDownRefresh();
    wx.hideLoading(); // 隐藏加载动画
    this.setData({ isRefreshing: false }); // 刷新完成
  },

  back() {
    wx.closeSocket({
      success: () => {
        console.log('WebSocket已断开连接');
      },
      fail: () => {
        wx.showToast({
          title: '没有更多内容了',
          icon: 'none'
        });
      }
    });
    wx.navigateBack({
      delta: 1 // 默认值是 1，表示返回上一页面
    });
  }
});
